import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { ExwarehousmanageService } from '../../xstorage-manage-services/exwarehous-manage.service';

@Component({
  selector: 'app-storage-exwarehous-edit',
  templateUrl: './storage-exwarehous-edit.component.html',
  styleUrls: ['./storage-exwarehous-edit.component.scss'],
  providers: [DatePipe]
})
export class StorageExwarehousEditComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {}; // 编辑详情

  flexLabelWidth: string = '108px';
  formParams: any = {
    type: '', // 出库类型
    whId: '', // 出库仓库
    quality: '', // 出库品质
    arrivalTime: '', // 预计到货日期
    contractEnclosure: '', // 附件
    remark: '', // 备注
    supId: '', // 供应商
    consignee: '', // 收货人
    tel: '', // 联系方式
    address: '', // 地址
    deliveryMethod: '', // 配送方式
    isFreight: '' // 邮费承担
  };
  
  outTypeOptions: any[] = []; // 出库类型Options
  supplierOptions: any[] = []; // 供应商Options
  warehouseOptions: any[] = []; // 仓库Options
  deliveryOptions: any[] = [...storageDeliveryMethodArrs]; // 配送方式Options

  associatedTableData: Array<any> = []; // 已选商品(出库明细)

  submitLoading = false;

  /**
   * 指定SN Modal
   * ----------------------------------------------------------------
   */
  isSnVisible = false;
  snItemArrs: any[] = [];
  snGoodsItem: any = {};
  snGoodsModalItem: any = {};

  /**
   * Bom Modal
   * ----------------------------------------------------------------
   */
  isBomVisible = false;
  bomGoodsId: number | string = '';
 
  /**
   * 选择商品 Modal
   * ----------------------------------------------------------------
   */
  isGoodVisible = false;
  goodTableParams: any = {
    code: '', // 查询条件
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };

  /**
   * ----------------------------------------------------------------
   * 商品选择 Table Check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArr: Array<any> = [];
 
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      let checkedItem = this.listOfCurrentPageData.find(item => item.id === id);
      let setIds = this.setOfCheckedArr.map(m => m.whGoodsId);
      this.setOfCheckedId.add(id);

      if (!setIds.includes(id)) {
        // isSnOpera 默认0
        this.setOfCheckedArr.push({
          ...checkedItem,
          whGoodsId: id,
          whGoodsState: checkedItem.state, // 商品状态
          whGoodsName: checkedItem.name, // 商品名称
          whGoodsCode: checkedItem.goodsCode, // 商品编号
          whGoodsTwoCode: checkedItem.code, // 商品69码
          type: checkedItem.snState === 0 ? 1 : 3, // 是否sn管控
          isSnOpera: 0,
          price: '',
          numer: ''
        });
      }
    } else {
      let delCheckedIndex = this.setOfCheckedArr.findIndex(item => item.whGoodsId === id);
      this.setOfCheckedId.delete(id);

      this.setOfCheckedArr.splice(delCheckedIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(tag => tag.state === 1);
    listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(tag => tag.state === 1);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private storageCommonService: StorageCommonService,
    private services: ExwarehousmanageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadExwarehouseTypeOption();
    this.loadStoreOptions();
    this.loadSupplierList();

    if (this.routeParams.id) {
      this.loadDetailData();
    }
  }

  // 查询出库类型
  async loadExwarehouseTypeOption() {
    const res: any = await this.commonService.getDictList('outbound_type');
    this.outTypeOptions = res || [];
  }

  // 查询仓库Options(状态为启用)
  async loadStoreOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data?.records?.length ? data?.records.filter((item: any) => item.state === 1) : [];
    } else {
      this.msg.error(message);
    }
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
  }

  /**
   * 选择更多商品
   * ----------------------------------------------------------------
   */
  async showMoreGoodsModal() {
    if (this.commonService.isEmpty(this.formParams.whId)) {
      this.msg.warning('请先选择出库仓库');
      return
    }
    await this.loadGoodTable();
    
    let arr = this.associatedTableData.map(m => m.whGoodsId);
    this.setOfCheckedId = new Set(arr);
    this.setOfCheckedArr = JSON.parse(JSON.stringify(this.associatedTableData));
    this.isGoodVisible = true;
  }

  async loadDetailData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data}: any = await this.services.getExwarehousDetailData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const { delivery, list } = data || {};

      this.detailsData = delivery || {};
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(delivery[key]) ? delivery[key] : '';
      }
      this.formParams.supId = !this.commonService.isEmpty(delivery.supId) ? Number(delivery.supId) : '';
      this.formParams.type = !this.commonService.isEmpty(delivery.type) ? String(delivery.type) : '';

      this.associatedTableData = list || [];
    }
  }

  /**
   * ----------------------------------------------------------------
   * 仓储商品 Modal
   * ----------------------------------------------------------------
   */
  async loadGoodTable() {
    let params = {
      whId: this.formParams.whId,
      code: this.goodTableParams.code,
      page: this.goodTableParams.page,
      pageSize: this.goodTableParams.pageSize
    }
    this.goodTableParams.loading = true;
    const {code, data, message}: any = await this.services.getStoreGoodsData(params);
    this.goodTableParams.loading = false;
    
    if (code === 0) {
      this.goodTableParams.tableData = data.records || [];
      this.goodTableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  searchGoodsData() {
    this.goodTableParams.page = 1;
    this.loadGoodTable();
  }

  resetGoodsData() {
    this.goodTableParams.code = '';
    this.goodTableParams.page = 1;
    this.loadGoodTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.goodTableParams.page = index;
    this.loadGoodTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.goodTableParams.page = 1;
    this.goodTableParams.pageSize = sizeNum;
    this.loadGoodTable();
  }

  // 关联已选
  relationSelected() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需关联项!');
      return
    }
    // return
    this.associatedTableData = JSON.parse(JSON.stringify(this.setOfCheckedArr));
    this.isGoodVisible = false;
  }

  /**
   * BOM Handle Modal
   * ----------------------------------------------------------------
   */
  showBomModal(item: any) {
    this.bomGoodsId = item.id;
    this.isBomVisible = true;
  }

  bomHandle(val: any) {
    let tmpIds = this.associatedTableData.map((m: any) => m.whGoodsId);
    let tmpTips: any[] = [];

    val.forEach((item: any) => {
      if (!tmpIds.includes(item.id)) {
        let obj = {
          ...item,
          whGoodsId: item.id,
          whGoodsState: item.state, // 商品状态
          whGoodsName: item.name, // 商品名称
          whGoodsCode: item.goodsCode, // 商品编号
          whGoodsTwoCode: item.code, // 商品69码
          type: item.snState === 0 ? 1 : 3, // 是否sn管控
          isSnOpera: 0,
          price: '',
          numer: ''
        }
        this.associatedTableData = this.associatedTableData.concat([...obj]);
      } else {
        tmpTips.push(item.name);
      }
    })

    if (tmpTips.length) {
      this.msg.warning(`商品 ${tmpTips.join('、')} 已存在`);
    }
    this.isGoodVisible = false;
  }

  /**
   * 指定sn信息 Modal 组件
   * ----------------------------------------------------------------
   */
  showSnInfoModal(item: any) {
    if (this.commonService.isEmpty(this.formParams.quality)) {
      this.msg.warning('请先选择出库品质');
      return
    }

    this.snGoodsItem = item;
    this.snGoodsModalItem = {
      goodsCode: item.whGoodsCode,
      whId: this.formParams.whId || '',
      quality: !this.commonService.isEmpty(this.formParams.quality) ? this.formParams.quality : '',
      number: item.number
    };
    this.snItemArrs = !this.commonService.isEmpty(item.itemSns) ? JSON.parse(item.itemSns) : [];
    this.isSnVisible = true;
  }

  appointSnData(val: any) {
    let setIndex = this.associatedTableData.findIndex(item => item.whGoodsId === this.snGoodsItem.whGoodsId);
    this.associatedTableData[setIndex].itemSns = val.itemSns;
    this.associatedTableData[setIndex].number = val.selectedArrs.length;
    this.associatedTableData[setIndex].isSnOpera = 1;
    this.associatedTableData[setIndex].type = 0; // 指定SN
    this.associatedTableData[setIndex].oldType = 1; // SN管控
  }

  clearSnData(val: any) {
    let setIndex = this.associatedTableData.findIndex(item => item.whGoodsId === this.snGoodsItem.whGoodsId);
    this.associatedTableData[setIndex].itemSns = '';
    this.associatedTableData[setIndex].number = '';
    this.associatedTableData[setIndex].isSnOpera = 0;
    this.associatedTableData[setIndex].type = 1; // SN管控
    this.associatedTableData[setIndex].oldType = 0; // 指定SN
  }

  /**
   * submit data
   * ----------------------------------------------------------------
   */
  verifData() {
    let isSubTable = this.associatedTableData.some(item => {
      return this.commonService.isEmpty(item.number) && this.commonService.isEmpty(item.itemSns);
    })
    const { type, whId, quality, deliveryMethod, isFreight } = this.formParams;
    if (this.commonService.isEmpty(type)) {
      this.msg.warning('请选择出库类型');
      return false;
    } else if (this.commonService.isEmpty(whId)) {
      this.msg.warning('请选择出库仓库');
      return false;
    } else if (this.commonService.isEmpty(quality)) {
      this.msg.warning('请选择出库品质');
      return false;
    } else if (this.commonService.isEmpty(deliveryMethod)) {
      this.msg.warning('请选择配送方式');
      return false;
    } else if (this.commonService.isEmpty(isFreight)) {
      this.msg.warning('请选择邮费承担');
      return false;
    } else if (!this.associatedTableData.length) {
      this.msg.warning('请选择出库明细');
      return false;
    } else if (isSubTable) {
      this.msg.warning('出库明细列表存在未填写预计出库数量');
      return false;
    } else {
      return true;
    }
  }

  async submitData() {
    if (!this.verifData()) {
      return
    }
    let arrs = this.associatedTableData.map(item => {
      return {
        isSnOpera: item.isSnOpera ? item.isSnOpera : 0, // 是否指定sn 0：否 1：是
        whGoodsId: item.whGoodsId,
        state: (this.routeParams.id && !this.commonService.isEmpty(item.lineState)) ? item.lineState : 0, // 状态 0正常(新增默认) 1已作废
        type: item.type,  // 商品列表type为分类 (注: 选择SN则为指定sn) // type: 0 指定SN 1SN管控 2多库位 3普通(新增默认)
        number: item.number, // 预计出库数量
        price: item.price, // 出库单价
        closeRemark: !this.commonService.isEmpty(item.closeRemark) ? item.closeRemark : '', // 关闭备注
        actualNumber: !this.commonService.isEmpty(item.actualNumber) ? item.actualNumber : '', // 实际出库数量
        itemSns: !this.commonService.isEmpty(item.itemSns) ? item.itemSns : '', // 商品SN号列表
        libraryText: !this.commonService.isEmpty(item.libraryText) ? item.libraryText : '', // 库位信息
        libraryId: !this.commonService.isEmpty(item.libraryId) ? item.libraryId : '' // 库位id
      }
    })

    let params: any = {
      isSplit: 0, // 0：添加、1：拆单
      delivery: {
        ...this.formParams
      },
      list: arrs
    }
    if (this.routeParams.type === 1 || this.routeParams.id) {
      params.delivery.id = this.routeParams.id;
    }
    // return

    // 0：新增 1：编辑
    let apiType = !this.commonService.isEmpty(params.delivery.id) ? 1 : 0;

    this.submitLoading = true;
    const {code, message}: any = await this.services.updateExwarehousData(params, apiType);
    this.submitLoading = false;

    if (code === 0) {
      this.msg.success('操作成功');
      this.pageBack();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    sum = this.associatedTableData.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  // 小计合计
  calcProductTotal() {
    let sum = 0;
    sum = this.associatedTableData.reduce((total: number, item: any) => {
      return (total || 0) + ((item.number || 0) * (item.price || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // timechange
  timeChange(val: any) {
    this.formParams.arrivalTime = val ? this.datePipe.transform(val, 'yyyy-MM-dd') : '';
  }

  // 删除已关联项
  deleteGoodItem(item: any) {
    this.associatedTableData = this.associatedTableData.filter(d => d.id !== item.id);
  }

  // 预计出库数量 change
  outNumberChange(val: any, index: number) {
    if (this.commonService.isEmpty(val)) {
      this.associatedTableData[index].isSnOpera = 0;
    }
  }

  pageBack() {
    history.back();
  }
}
